//
//  JYJViewController.m
//  HaierGMS_APP
//
//  Created by 堂堂 on 16/10/24.
//  Copyright © 2016年 堂堂. All rights reserved.
//

#import "JYJViewController.h"
#import "UIColor+Hex.h"
#import "SignViewController.h"
#import "MBProgressHUD+MJ.h"
#import "UserDefaultUtil.h"
#import "HttpReauestParam.h"
#import "AFHTTPRequestOperationManager.h"
#import "UIColor+Hex.h"
@interface JYJViewController ()

@end

@implementation JYJViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _code_text.delegate =self;

    [self.contentView setBackgroundColor:[UIColor colorWithHexString:@"#f2f2f2"]];
    
    [_limitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_limitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [_limitBtn setTitle:@"核销" forState:UIControlStateNormal];
    [_limitBtn setTitle:@"核销" forState:UIControlStateSelected];
    [_limitBtn setBackgroundImage:[self createImageWithColor:[UIColor colorWithHexString:@"#ff7e00"]] forState:UIControlStateNormal];
    _limitBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [_limitBtn addTarget:self action:@selector(sendCode) forControlEvents:UIControlEventTouchUpInside];
    
    //获取验证码按钮
    [_codeBtn setTitleColor:[UIColor colorWithHexString:@"#ff7e00"] forState:UIControlStateNormal];
    [_codeBtn setTitleColor:[UIColor colorWithHexString:@"#ff7e00"] forState:UIControlStateSelected];
    _codeBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [_codeBtn.layer setBorderColor:[UIColor colorWithHexString:@"#ff7e00"].CGColor];
    [_codeBtn.layer setBorderWidth:1];
    
    [_codeBtn addTarget:self action:@selector(getCode) forControlEvents:UIControlEventTouchUpInside];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (UIImage*) createImageWithColor: (UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage*theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    return theImage;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if([textField isFirstResponder]){
        [textField  resignFirstResponder];
    }
    return YES;
}
- (IBAction)touchView:(id)sender {
    [self.view endEditing:YES];  
}

- (IBAction)back_click:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)getCode{
   
    NSDictionary *data1 = @{@"setOuterId":_serviceNo,@"setBizType":@"9001"};
    
    NSDictionary *data2 = @{@"setOuterId":@"String",@"setBizType":@"Long"};
    NSDictionary *dic = @{@"appkey":@"23307253",@"secret":@"e096f604a61d582f15ed90ba262a171d",@"url":@"http://gw.api.taobao.com/router/rest",@"requestClass":@"VmarketEticketFlowResendRequest",@"requestSubClass":[self stringToJSONData:data2 ],@"requestData":[self stringToJSONData:data1 ]};
    
    
  
    
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manage.requestSerializer setValue:@"UTF-8" forHTTPHeaderField:@"Accept-Encoding"];
    [MBProgressHUD showMessage:@"获取验证码"];
    [manage POST:@"http://27.223.99.200:8080/rrs/route/tmall_http_service.do" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [MBProgressHUD hideHUD];
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        NSString *datastr = data[@"result"][@"body"];
        
        NSDictionary * data2 = [NSJSONSerialization JSONObjectWithData:[datastr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        if ([data2[@"vmarket_eticket_flow_resend_response"][@"retCode"] integerValue] == 1) {
            [MBProgressHUD showSuccess:@"获取验证码成功"];
        }else{
            [MBProgressHUD showSuccess:@"获取验证码失败"];
        }
        NSLog(@"%@",data);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络连接失败"];
    }];
}
-(void)sendCode{
    
    if([_code_text.text isEqualToString:@""]){
        [MBProgressHUD showError:@"请输入验证码"];
        return;
    }
    
    NSString *code = _code_text.text;
    NSString *name = [UserDefaultUtil getData:USER_NAME];
    NSDictionary *data = @{@"setOuterId":_serviceNo,@"setBizType":@"9001",@"setCode":code,@"setOperator":name};
    

    NSDictionary *dic = @{@"appkey":@"23307253",@"secret":@"e096f604a61d582f15ed90ba262a171d",@"url":@"http://gw.api.taobao.com/router/rest",@"requestClass":@"VmarketEticketFlowConsumeRequest",@"requestSubClass":@"{\"setOuterId\":\"String\",\"setCode\":\"String\",\"setBizType\":\"Long\",\"setOperator\":\"String\"}",@"requestData":[self stringToJSONData:data ]};
    
    
    
    
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manage.requestSerializer setValue:@"UTF-8" forHTTPHeaderField:@"Accept-Encoding"];
    [MBProgressHUD showMessage:@"核销"];
    [manage POST:@"http://27.223.99.200:8080/rrs/route/tmall_http_service.do" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [MBProgressHUD hideHUD];
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];

        NSString *datastr = data[@"result"][@"body"];
        
        NSDictionary * data2 = [NSJSONSerialization JSONObjectWithData:[datastr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        if ([data2[@"vmarket_eticket_flow_consume_response"][@"retCode"] integerValue] == 1) {
            [MBProgressHUD showSuccess:@"核销成功"];
            [self sendHX];
        }else{
            [MBProgressHUD showSuccess:@"核销失败"];
        }
        NSLog(@"%@",data);
        
        
        NSLog(@"%@",data);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络连接失败"];
    }];
}

-(NSString*)stringToJSONData:(id)infoDict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    
    NSString *jsonString = @"";
    
    if (! jsonData)
    {
        NSLog(@"Got an error: %@", error);
    }else
    {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符
    
    [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    return jsonString;
}

-(void)sendHX{
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:_serviceNo forKey:@"serviceNo"];
    [dic setObject:[UserDefaultUtil getUserId] forKey:@"identifier"];
    
    HttpReauestParam *param = [[HttpReauestParam alloc] initWithData:@"mao_hx_notice" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        //核销成功
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
        SignViewController *orderSign = [story instantiateViewControllerWithIdentifier:@"sign_opp"];
        orderSign.serviceNo = _serviceNo;
        orderSign.popCount = 2;
        [self.navigationController pushViewController:orderSign animated:YES];
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //核销成功
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
        SignViewController *orderSign = [story instantiateViewControllerWithIdentifier:@"sign_opp"];
        orderSign.serviceNo = _serviceNo;
        orderSign.popCount = 2;
        [self.navigationController pushViewController:orderSign animated:YES];
        
        
    }];
}
-(NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
@end
